/**
 * Created by root on 17-7-31.
 */
var schedule = require('node-schedule');
var http = require('../utils/http');
var logger = require('../config/log4js');
var cheerio = require('cheerio');
var ipListService = require('../service/ipListService');

var jobs = [];

function indexTask() {
    var rule = new schedule.RecurrenceRule();
    rule.minute = [1, 16, 31, 46];
    var job = schedule.scheduleJob(rule, function () {
        logger.access.info('data5uHttpProxy定时任务: ' + new Date());
        http.data5uGet("www.data5u.com/free/index.html", function (result) {

            if (result.statusCode === 200) {
                var $ = cheerio.load(result.body);
                $(".l2").each(function () {
                    var ipList = $(this).children();

                    logger.access.info($(ipList[0]).text() + ":" + $(ipList[1]).text() + " " + $(ipList[3]).text());
                    if ($(ipList[3]).text() === 'HTTP') {
                        ipListService.addIP({
                            ip: $(ipList[0]).text(),
                            port: $(ipList[1]).text(),
                            type: 0
                        }, function (result) {
                        });
                    }
                    if ($(ipList[3]).text() === 'HTTPS') {
                        ipListService.addIP({
                            ip: $(ipList[0]).text(),
                            port: $(ipList[1]).text(),
                            type: 1
                        }, function (result) {
                        });
                    }
                    if ($(ipList[3]).text() === '') {
                        ipListService.addIP({
                            ip: $(ipList[0]).text(),
                            port: $(ipList[1]).text(),
                            type: null
                        }, function (result) {
                        });
                    }
                });

            } else {
                logger.error.info(result);
            }
        });
    });
    jobs.push(job);
}

module.exports = {
    start : function () {

        indexTask();
        logger.access.info('data5uHttpProxyTask Start!');
    },
    stop : function () {
        for (var i = 0; i < jobs.length; i++) {
            jobs[i].cancel();
        }
    }
}
